<template>
  <div class="app-container">
    <div class="filter-container">
      <router-link to="/admin/student_add/">
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit">
           增加
         </el-button>
      </router-link>

      <el-input v-model="listQuery.name" placeholder="请输入名称" style="width:250px;" class="filter-item" @keyup.enter.native="handleFilter" />
    <!--  <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select> -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button v-waves:loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-upload2" @click="handleImport">
        导入
      </el-button>
      <el-button v-waves:loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    <!--  <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" width="60" sortable="custom" align="center"  :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名称" min-width="90"  align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="真实姓名" min-width="70"  align="center">
        <template slot-scope="{row}">
          <span>{{ row.realname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像"  align="center" width="80">
        <template slot-scope="{row}">
          <span>
            <el-image :src="$baseUrl+row.photo" lazy class="img50" fit="cover">
              <div slot="placeholder" class="image-slot">
                      <i class="el-icon-loading" />
              </div>
              <div slot="error" class="image-slot"><i class="el-icon-picture-outline"></i></div>
            </el-image>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="角色"  min-width="50" align="center">
        <template slot-scope="{row}">
          <span>{{ row.role }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班级"  align="center">
        <template slot-scope="{row}">
          <span>{{ row.classs?row.classs.name:'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="籍贯"  align="center">
        <template slot-scope="{row}">
          <span>{{ row.area?row.area.name:'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话"  align="center">
        <template slot-scope="{row}">
          <span>{{ row.tel }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Email"  align="center">
        <template slot-scope="{row}">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" min-width="40" align="center">
        <template slot-scope="{row}">
          <span>{{ row.gender }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生日" width="80"   align="center">
        <template slot-scope="{row}">
          <span>{{ row.birthday }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <router-link :to="{path:'/admin/student_update/', query: {id:row.id}}">
            <el-button type="primary" size="mini">
             修改
            </el-button>
          </router-link>
         <!-- <el-button v-if="row.status!='published'" size="mini" type="success" @click="handleModifyStatus(row,'published')">
            Publish
          </el-button>
          <el-button v-if="row.status!='draft'" size="mini" @click="handleModifyStatus(row,'draft')">
            Draft
          </el-button> -->
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="postForm" :rules="rules" :model="postForm" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="班级" label-width="60px" prop="classsId" >
          <el-cascader v-model="postForm.classsId" :options="classs" :props="cascaderProps" clearable placeholder="请选择"></el-cascader>
        </el-form-item>
        <el-form-item label="选择文件" >
         <el-upload
           class="upload-demo"
           accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
           :action="$baseUrl+'/api/admin/student/import'"
           ref="upload"
           :data="postForm"
           :headers = "headers"
           :auto-upload="false"
           multiple
           :before-upload="beforeUpload"
           :limit="1">
           <el-button size="small" type="primary">选取文件</el-button>
           <div slot="tip" class="el-upload__tip">只能上传xlsx文件，且不超过500kb</div>
         </el-upload>
        </el-form-item>
     </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">
        取消
      </el-button>
      <el-button type="primary" @click="submitForm()">
        提交
      </el-button>
    </div>
   </el-dialog>
  </div>
</template>

<script>
import API from '@/api/student'
import classsAPI from '@/api/classs'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getToken } from '@/utils/auth'

const defaultForm = {
   classsId: null
}

export default {
  name: 'student',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {

    }
  },
  data() {
    return {
      postForm: Object.assign({}, defaultForm),
      rules: {
           classsId: [{ required: true, message: '请选择班级', trigger: 'blur' }]
      },
      classs: [],
      cascaderProps: {value: 'id',label:'name',children:'childs',emitPath:false},
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        studentname: undefined,
        sort: '+id'
      },
      importanceOptions: [],

      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改 ',
        create: '增加',
        import: '导入'
      },
      dialogPvVisible: false,
      pvData: [],
      downloadLoading: false,
      headers:{
        Authorization: "Bearer "+ getToken()  //从cookie里获取token，并赋值  Authorization ，而不是token
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      API.fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 10)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    handleDelete(row, index) {
      this.$confirm('确认删除吗?', '提醒', {confirmButtonText:'确定',cancelButtonText: '取消',type: 'warning'}).then(() => { //点击确定的操作(调用接口)
         API.delete(row.id).then(() => {
           this.$notify({
             title: '提示',
             message: '删除成功！',
             type: 'success',
             duration: 2000
           })
           this.list.splice(index, 1)
         })

      }).catch(() => { })//几点取消的提醒

    },
    handleImport() {
      this.getClasss()
     // this.resetTemp()
      this.dialogStatus = 'import'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['postForm'].clearValidate()
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['id', 'name', 'intro']
        const filterVal = ['id', 'name', 'intro']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'student-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    getClasss() {
      classsAPI.fetchList().then(response => {
        if (!response.data.items) return
        this.classs = response.data.items;
      })
    },
    beforeUpload(file){
      if(file.size<1){
        this.$notify({
          title: '提示',
          message: '选择文件！',
          type: 'success',
          duration: 2000
        })
        return
      }
    },
    submitForm() {
      this.$refs["postForm"].validate(valid => {
        if (valid) {
          this.$refs['upload'].submit()
          this.dialogFormVisible = false
          getList()
        }else {
            console.log('error submit!!')
            return false
          }
       })
    }
  }
}
</script>
